{
 "cells": [
  {
   "cell_type": "code",
   "id": "5f77393fd79d40f0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T02:53:42.444986Z",
     "start_time": "2025-04-29T02:53:42.438172Z"
    }
   },
   "source": [
    "import torch\n",
    "\n",
    "# 创建一个需要计算梯度的张量\n",
    "x = torch.tensor([1.0], requires_grad=True)\n",
    "y = x ** 2\n",
    "\n",
    "# 正常情况下，计算梯度\n",
    "y.backward()\n",
    "print(\"正常情况下的梯度:\", x.grad)\n",
    "\n",
    "# 清零梯度\n",
    "# x.grad.zero_()\n",
    "print(\"halo\")\n",
    "\n",
    "\n",
    "# 在 torch.no_grad() 上下文环境中进行操作\n",
    "with torch.no_grad():\n",
    "    z = x ** 2\n",
    "    # 由于在 no_grad 环境中，z 不会跟踪梯度\n",
    "    print(\"z 是否需要梯度:\", z.requires_grad)\n",
    "\n",
    "    # 手动更新 x 的值\n",
    "    x += 1\n",
    "\n",
    "    # 在 no_grad 环境中，不会计算梯度\n",
    "    # 这里尝试对 z 进行反向传播会报错\n",
    "    try:\n",
    "        z.backward()\n",
    "    except RuntimeError as e:\n",
    "        print(\"在 no_grad 环境中反向传播报错:\", e)\n",
    "\n",
    "# 验证 x 的梯度是否仍然为零\n",
    "print(\"更新后 x 的梯度:\", x.grad)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正常情况下的梯度: tensor([2.])\n",
      "halo\n",
      "z 是否需要梯度: False\n",
      "在 no_grad 环境中反向传播报错: element 0 of tensors does not require grad and does not have a grad_fn\n",
      "更新后 x 的梯度: tensor([2.])\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "8b131b8a6ffd953e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T03:18:01.677819Z",
     "start_time": "2025-04-29T03:18:01.673384Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x_arary = torch.ones(4,2)\n",
    "print(x_arary)"
   ],
   "id": "59a028e076498d71",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1.],\n",
      "        [1., 1.],\n",
      "        [1., 1.],\n",
      "        [1., 1.]])\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T04:00:04.788307Z",
     "start_time": "2025-04-29T04:00:04.781538Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x = torch.tensor([3.], requires_grad=True)\n",
    "y = x ** 2\n",
    "print(f\"x: {x} \")\n",
    "print(f\"y: {y}\")\n",
    "\n",
    "grad_1 = torch.autograd.grad(y, x, create_graph=True)\n",
    "print(f\"grad_1: {grad_1}\")\n",
    "\n",
    "\n",
    "grad_2 = torch.autograd.grad(grad_1[0], x)\n",
    "print(f\"grad_2: {grad_2}\")\n",
    "\n",
    "\n"
   ],
   "id": "bfeccba416e189ca",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x: tensor([3.], requires_grad=True) \n",
      "y: tensor([9.], grad_fn=<PowBackward0>)\n",
      "grad_1: (tensor([6.], grad_fn=<MulBackward0>),)\n",
      "grad_2: (tensor([2.]),)\n"
     ]
    }
   ],
   "execution_count": 44
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T04:01:20.596928Z",
     "start_time": "2025-04-29T04:01:20.591256Z"
    }
   },
   "cell_type": "code",
   "source": [
    "a = torch.ones((1))\n",
    "print(f\"id(a) :{id(a)}, a={a}\")\n",
    "\n",
    "a += torch.ones((1))\n",
    "print(f\"id(a) :{id(a)}, a={a}\")"
   ],
   "id": "ec410a26b1c3ca5e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "id(a) :2808020236192, a=tensor([1.])\n",
      "id(a) :2808020236192, a=tensor([2.])\n"
     ]
    }
   ],
   "execution_count": 51
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "bfc7eed2ceb0836f"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (pytorch)",
   "language": "python",
   "name": "pytorch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
